package com.gl.framework.manager.factory;

import java.util.Date;
import java.util.TimerTask;

import com.gl.portal.system.service.SysLoginLogService;
import com.gl.portal.system.service.SysOperLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gl.common.constant.Constants;
import com.gl.common.util.ip.AddressUtils;
import com.gl.common.util.ip.IpUtils;
import com.gl.common.util.log.LogUtils;
import com.gl.common.util.servlet.ServletUtils;
import com.gl.common.util.spring.SpringUtils;
import com.gl.portal.system.entity.SysLoginLog;
import com.gl.portal.system.entity.SysOperLog;

import eu.bitwalker.useragentutils.UserAgent;

/**
 * 异步工厂（产生任务用）
 */
public class AsyncFactory {
	private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

	/**
	 * 记录登陆信息
	 *
	 * @param loginName 登录账号
	 * @param status    状态
	 * @param message   消息
	 * @param args      列表
	 * @return 任务task
	 */
	public static TimerTask recordLoginLog(final String loginName, final String status, final String message, final Object... args) {
		final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
		final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
		return new TimerTask() {
			@Override
			public void run() {
				String address = AddressUtils.getRealAddressByIP(ip);
				StringBuilder s = new StringBuilder();
				s.append(LogUtils.getBlock(ip));
				s.append(address);
				s.append(LogUtils.getBlock(loginName));
				s.append(LogUtils.getBlock(status));
				s.append(LogUtils.getBlock(message));
				// 打印信息到日志
				sys_user_logger.info(s.toString(), args);
				// 获取客户端操作系统
				String os = userAgent.getOperatingSystem().getName();
				// 获取客户端浏览器
				String browser = userAgent.getBrowser().getName();
				// 封装对象
				SysLoginLog loginLog = new SysLoginLog();
				loginLog.setLoginName(loginName);
				loginLog.setIpaddr(ip);
				loginLog.setLoginLocation(address);
				loginLog.setBrowser(browser);
				loginLog.setOs(os);
				loginLog.setMsg(message);
				loginLog.setLoginTime(new Date());
				// 日志状态
				if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
					loginLog.setStatus(Constants.SUCCESS);
				} else if (Constants.LOGIN_FAIL.equals(status)) {
					loginLog.setStatus(Constants.FAIL);
				}
				// 插入数据
				SpringUtils.getBean(SysLoginLogService.class).saveLoginLog(loginLog);
			}
		};
	}

	/**
	 * 操作日志记录
	 *
	 * @param operLog 操作日志信息
	 * @return 任务task
	 */
	public static TimerTask recordOper(final SysOperLog operLog) {
		return new TimerTask() {
			@Override
			public void run() {
				// 远程查询操作地点
				operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
				SpringUtils.getBean(SysOperLogService.class).saveOperlog(operLog);
			}
		};
	}
}
